import 'package:app_30/net/dio_utils.dart';
import 'package:app_30/net/http_api.dart';
import 'package:app_30/res/constant.dart';
import 'package:app_30/res/gaps.dart';
import 'package:app_30/util/cache_utils.dart';
import 'package:app_30/util/change_notifier_manage.dart';
import 'package:app_30/util/dialog_utils.dart';
import 'package:app_30/util/other_utils.dart';
import 'package:app_30/util/toast_utils.dart';
import 'package:app_30/widgets/my_app_bar.dart';
import 'package:app_30/widgets/my_button.dart';
import 'package:app_30/widgets/my_scroll_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'my_text_field.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage>
    with ChangeNotifierMixin<RegisterPage> {
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();
  final FocusNode _nodeText4 = FocusNode();
  final FocusNode _nodeText5 = FocusNode();

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _tuijianController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _vCodeController = TextEditingController();

  bool _clickable = false;

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _nameController: callbacks,
      _passwordController: callbacks,
      _tuijianController: callbacks,
      _phoneController: callbacks,
      _vCodeController: callbacks,
      _nodeText1: null,
      _nodeText2: null,
      _nodeText3: null,
      _nodeText4: null,
      _nodeText5: null,
    };
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      /// 显示状态栏和导航栏
      SystemChrome.setEnabledSystemUIOverlays(
          [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    });
  }

  void _verify() {
    final String name = _nameController.text;
    final String password = _passwordController.text;
    final String tuijian = _tuijianController.text;
    final String code = _vCodeController.text;
    bool clickable = true;
    if (name.isEmpty || name.length < 4) {
      clickable = false;
    }
    if (password.isEmpty || password.length < 4) {
      clickable = false;
    }
    if ("1" == getRegcode() && (code.isEmpty || code.length < 6)) {
      clickable = false;
    }
    if (tuijian.isNotEmpty && tuijian.length < 4) {
      clickable = false;
    }

    /// 状态不一样再刷新，避免不必要的setState
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: '注册',
      ),
      body: MyScrollView(
        keyboardConfig: Utils.getKeyboardActionsConfig(context, <FocusNode>[
          _nodeText1,
          _nodeText2,
          _nodeText3,
          _nodeText4,
          _nodeText5
        ]),
        padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 20.0),
        children: _buildBody,
      ),
    );
  }

  List<Widget> get _buildBody => <Widget>[
        Row(
          children: [
            Text("用户名 :", style: TextStyle(fontSize: 15.5, color: Colors.grey)),
            SizedBox(
              width: 8,
            ),
            Flexible(
              child: MyTextField(
                focusNode: _nodeText1,
                controller: _nameController,
                maxLength: 20,
                hintText: '请输入用户名',
              ),
            )
          ],
        ),
        Row(
          children: [
            Text("密 码  :",
                style: TextStyle(fontSize: 15.5, color: Colors.grey)),
            SizedBox(
              width: 8,
            ),
            Flexible(
              child: MyTextField(
                focusNode: _nodeText2,
                controller: _passwordController,
                keyboardType: TextInputType.visiblePassword,
                maxLength: 20,
                isInputPwd: true,
                hintText: '请输入密码',
              ),
            )
          ],
        ),
        Row(
          children: [
            Text("推荐人 :", style: TextStyle(fontSize: 15.5, color: Colors.grey)),
            SizedBox(
              width: 8,
            ),
            Flexible(
              child: MyTextField(
                focusNode: _nodeText3,
                controller: _tuijianController,
                keyboardType: TextInputType.visiblePassword,
                maxLength: 20,
                hintText: '请输入推荐人',
              ),
            )
          ],
        ),
        Gaps.vGap24,
        Row(
          children: [
            Text("手机号 :", style: TextStyle(fontSize: 15.5, color: Colors.grey)),
            SizedBox(
              width: 8,
            ),
            Flexible(
              child: MyTextField(
                focusNode: _nodeText4,
                controller: _phoneController,
                maxLength: 11,
                hintText: '请输入手机号',
              ),
            )
          ],
        ),
        Row(
          children: [
            Text("验证码 :", style: TextStyle(fontSize: 15.5, color: Colors.grey)),
            SizedBox(
              width: 8,
            ),
            Flexible(
              child: MyTextField(
                focusNode: _nodeText5,
                controller: _vCodeController,
                keyboardType: TextInputType.number,
                getVCode: () async {
                  if (_phoneController.text.length == 11) {
                    sendCode();
                    return true;
                  } else {
                    Toast.show('请输入合法的手机号');
                    return false;
                  }
                },
                maxLength: 6,
                hintText: '请输入验证码',
              ),
            )
          ],
        ),
        Gaps.vGap24,
        MyButton(
          key: const Key('login'),
          onPressed: _clickable ? _getregist : _checkText,
          text: '注册',
        ),
      ];

  void _checkText() {
    final String name = _nameController.text;
    final String password = _passwordController.text;
    final String tuijian = _tuijianController.text;
    final String code = _vCodeController.text;

    if (name.isEmpty || name.length < 4) {
      Toast.show('账号长度为4到20!');
      return;
    }
    if (password.isEmpty || password.length < 4) {
      Toast.show('密码长度为4到20!');
      return;
    }
    if ("1" == getRegcode() && (code.isEmpty || code.length < 6)) {
      Toast.show('请输入合法的验证码');
      return;
    }
    if (tuijian.isNotEmpty && tuijian.length < 4) {
      Toast.show('推荐人账号长度为4到20!');
      return;
    }
  }

  void gotoHome() {
    Navigator.of(context).pop();
  }

  void _getregist() async {
    final String name = _nameController.text;
    final String password = _passwordController.text;
    final String tuijian = _tuijianController.text;
    final String phone = _phoneController.text;
    final String code = _vCodeController.text;

    Map<String, dynamic> map = Map();
    map['user'] = "${name}";
    map['password'] = '${password}';
    map['mac'] = getIdentifier();
    map['app'] = getPlatform();
    map['tjr'] = '${tuijian}';
    map['phonenumber'] = '${phone}';
    map['regcode'] = '${code}';
    map['token'] = Constant.token;
    map['time'] = '';

    await DioUtils.instance.requestNetwork<String>(
      Method.post,
      HttpApi.zhuce,
      params: map,
      onSuccess: (data) {
        setUser(name);
        setPwd(password);
        gotoHome();
      },
      onError: (_, __) {
        showSingleDialog(
          context,
          '${__}',
        );
      },
    );
  }

  void sendCode() async {
    final String phone = _phoneController.text;
    Map<String, dynamic> map = Map();
    map['mac'] = getIdentifier();
    map['app'] = getPlatform();
    map['phonenumber'] = '${phone}';
    map['token'] = '';
    map['time'] = '';

    await DioUtils.instance.requestNetwork<String>(
      Method.post,
      HttpApi.phoneregcode,
      params: map,
      onSuccess: (data) {
        Toast.show('发送成功');
      },
      onError: (_, __) {
        showSingleDialog(
          context,
          '${__}',
        );
      },
    );
  }
}
